<template>
  <div class="page-operation">
    <el-button type="primary" @click="handleInsertProduct">Insert Product</el-button>
    <el-button :disabled="productIDs.length < 1" @click="handlePutOnBatch">Batch Put On</el-button>
    <el-button :disabled="productIDs.length < 1" @click="handlePutOffBatch">Batch Put Off</el-button>
    <el-button @click="handleExportToExcel">Export To Excel</el-button>
  </div>
  <div class="page-filter">
    <el-form inline :disabled="isLoadingProductList" @submit.prevent="handleSearch">
      <el-form-item label="Status">
        <el-select v-model="productListParams.type">
          <el-option
            v-for="item in statusList"
            :key="item.type"
            :value="item.type"
            :label="item.name"
          >
            <span>{{ item.name }}</span>
            <span style="float: right">{{ item.count }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="Category">
        <el-cascader
          clearable
          v-model="productListParams.cate_id"
          :options="categoryList"
          :props="{
            label: 'cate_name',
            value: 'id',
            emitPath: false,
          }"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="Name">
        <el-input v-model="productListParams.store_name"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">Search</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="page-container" v-loading="isLoadingProductList">
    <el-table border :data="productList" @selection-change="handleSelectProduct">
      <el-table-column type="selection" width="55" />
      <el-table-column label="ID" prop="id" width="100px"></el-table-column>
      <el-table-column label="Cover" width="120px">
        <template #default="scope">
          <el-image :src="scope.row.image" style="width: 50px; height: 50px"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="Name" prop="store_name"></el-table-column>
      <el-table-column
        label="Category"
        prop="cate_name"
        :formatter="(row: ProductInfoType) => row.cate_name.replaceAll(',', '，')"
      ></el-table-column>
      <el-table-column label="Price" prop="price"></el-table-column>
      <el-table-column label="Stock" prop="stock"></el-table-column>
      <el-table-column label="Sold" prop="sales"></el-table-column>
      <el-table-column label="Status">
        <template #default="scope">
          <el-switch
            :active-value="1"
            :inactive-value="0"
            v-model="scope.row.is_show"
            @change="handleSetProductStatus(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="Action" fixed="right" width="240">
        <template #default="{ row }">
          <el-link type="primary" @click="handleEditProduct(row)">Edit</el-link>
          <el-divider direction="vertical"></el-divider>
          <el-link type="primary" @click="handleViewComment(row)">View Comment</el-link>
          <el-divider direction="vertical"></el-divider>
          <el-link type="danger" @click="handleDeleteProduct(row)">
            {{
              row.is_del ? 'Restore' : 'Delete'
            }}
          </el-link>
        </template>
      </el-table-column>
    </el-table>

    <Pagination
      v-model:index="productListParams.page"
      v-model:size="productListParams.limit"
      :total="productCount"
      :on-change="handleGetProductList"
    />
  </div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import {
  delProduct,
  getProductList,
  getStatusList,
  putProductOffBatch,
  putProductOnBatch,
  setProductStatus,
} from '@/api/product'
import useCategoryList from '@/pages/product/category/index'
import Pagination from '@/components/pagination/index.vue'
import xlsx from 'xlsx'
import router from '@/router/'
import { ElMessage } from 'element-plus'
import { productListParams, handleGetProductList, productCount, isLoadingProductList, productList } from './index'


// 1. get status list
const statusList = ref<ProductStatusType[]>([{ name: '全部', type: 0 }])

getStatusList().then(res => {
  statusList.value = [{ name: '全部', type: 0 }, ...res.list]
})

// 2. get category list
const { categoryList, handleGetCategoryList } = useCategoryList()
handleGetCategoryList()

// 3. get product list
handleGetProductList()

function handleSearch() {
  productListParams.value.page = 1
  handleGetProductList()
}

// 4. insert/edit product
function handleInsertProduct() {
  router.push('/product/insert')
}

function handleEditProduct(product: ProductInfoType) {
  router.push(`/product/insert?id=${product.id}`)
}

// 5. put on/off batch
const productIDs = ref<number[]>([])

function handleSelectProduct(selection: ProductInfoType[]) {
  productIDs.value = selection.map(item => item.id)
}

function handlePutOnBatch() {
  putProductOnBatch({ ids: productIDs.value }).then(() => {
    handleGetProductList()
  })
}

function handlePutOffBatch() {
  putProductOffBatch({ ids: productIDs.value }).then(() => {
    handleGetProductList()
  })
}

// 6. export excel
function handleExportToExcel() {
  const wb = xlsx.utils.book_new()
  const ws = xlsx.utils.json_to_sheet(productList.value)
  xlsx.utils.book_append_sheet(wb, ws, 'Sheet1')
  xlsx.writeFile(wb, 'product.xlsx')
}

// 7. set product status
function handleSetProductStatus(product: ProductInfoType) {
  setProductStatus(product.id, product.is_show).then(() => {
    handleGetProductList()
  })
}

// 8. delete product
function handleDeleteProduct(product: ProductInfoType) {
  const { is_del: isDel, id } = product
  delProduct(id).then(() => {
    handleGetProductList()
    ElMessage.success({ message: isDel ? 'Restore Success' : 'Delete Success' })
  })
}

// 9. view comment
function handleViewComment(product: ProductInfoType) {
  router.push(`/product/comment?id=${product.id}`)
}
</script>
